//
//  WLExchangeScoreVController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/11.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLExchangeScoreVController.h"
#import "WLTelecomProductModel.h"
#import "WLTelecomProductCell.h"
#import "WLMyCardsVController.h"

@interface WLExchangeScoreVController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tbProducts;
@property (nonatomic, strong) NSMutableArray *arrProduct;
@property (nonatomic, assign) NSInteger reqPage;
@property (nonatomic, weak) UILabel *labScore;

@end

@implementation WLExchangeScoreVController


- (void)dealloc
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"兑换电信充值卡";
    
    UIButton *btnMyCard = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    btnMyCard.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:14];
    [btnMyCard setTitleColor:wlblueColor forState:UIControlStateNormal];
    [btnMyCard setTitle:@"我的卡券" forState:UIControlStateNormal];
    [btnMyCard addTarget:self action:@selector(myCardAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithCustomView:btnMyCard];
    self.navigationItem.rightBarButtonItem = rightBar;
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(20), WIDTH_SCREEN_WL-WLScaleX(32), WLScaleX(28))];
    topView.backgroundColor = wlUIColorRGB(0xF2F2F2);
    topView.layer.cornerRadius = 5;
    topView.layer.masksToBounds = YES;
    [self.view addSubview:topView];
    
    UIImageView *ivTip = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(10), WLScaleX(6), WLScaleX(16), WLScaleX(16))];
    ivTip.image = [UIImage imageNamed:@"lab_headTip"];
    [topView addSubview:ivTip];
    
    UILabel *labScore = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(32), WLScaleX(4), topView.bounds.size.width-WLScaleX(48), WLScaleX(20))];
    labScore.font = [WLCommonTool fontTypePingFangSCRegular:11];
    labScore.textColor = wlLightTextColor;
    [topView addSubview:labScore];
    _labScore = labScore;
    [self refreshCurrentScore];
    
    WLWkSelf
    _arrProduct = [[NSMutableArray alloc] init];
    _reqPage = 1;
    _tbProducts = [[UITableView alloc] init];
    _tbProducts.backgroundColor = wlUIColorRGB(0xFAFAFA);
    _tbProducts.delegate = self;
    _tbProducts.dataSource = self;
    _tbProducts.rowHeight = WLScaleX(96);
    _tbProducts.tableFooterView = [UIView new];
    [self.view addSubview:_tbProducts];
    [_tbProducts mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom).offset(WLScaleX(5));
        make.left.bottom.right.equalTo(weakSelf.view);
    }];
    _tbProducts.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.tbProducts.mj_footer = nil;
        [weakSelf.arrProduct removeAllObjects];
        weakSelf.reqPage = 1;
        [weakSelf reqTelecomProducts];
    }];
    
    [self reqTelecomProducts];
}
- (void)refreshCurrentScore {
    
    NSString *strTip = @"";
    if (self.enableScore !=nil&&[self.enableScore isKindOfClass:[NSNull class]]==NO) {
        strTip = [NSString stringWithFormat:@"您当前可兑换的积分额度为：%@积分",self.enableScore];
    }
    else
    {
        strTip = @"您当前可兑换的积分额度为：0积分";
    }
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:strTip];
    [attStr addAttribute:NSForegroundColorAttributeName value:wlblueColor range:NSMakeRange(13, attStr.length-15)];
    _labScore.attributedText = attStr;

}
- (void)addFooterRefresh
{
    WLWkSelf
    _tbProducts.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqTelecomProducts];
    }];
}

 -(void)reqTelecomProducts
{
    WLWkSelf
    NSDictionary *conditions = @{@"enable":@"",@"id":@"",@"name":@"",@"endTime":@""};
    NSDictionary *pages = @{@"page":[NSNumber numberWithInteger:_reqPage],@"num":@10};
    NSDictionary *paramsp = @{@"conditions":conditions,@"page":pages};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"product/list/condition" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.tbProducts.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"count"] integerValue];
        if (strongSelf.reqPage==1&&productCount>10)
        {
            [strongSelf addFooterRefresh];
        }
        NSArray *arrPros = [WLTelecomProductModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        if (arrPros.count>0) {
            [strongSelf.arrProduct addObjectsFromArray:arrPros];
            if (strongSelf.arrProduct.count >= productCount) {
                [strongSelf.tbProducts.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.tbProducts.mj_footer endRefreshing];
            }
            [strongSelf.tbProducts reloadData];
        }
        else
        {
            [strongSelf.tbProducts.mj_footer endRefreshingWithNoMoreData];
        }
        strongSelf.reqPage += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf.tbProducts.mj_header endRefreshing];
        [weakSelf.tbProducts.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf.tbProducts.mj_header endRefreshing];
        [weakSelf.tbProducts.mj_footer endRefreshing];
    } inView:(_reqPage==1&&_tbProducts.mj_header.isRefreshing==NO)?self.view:nil];
}

- (void)myCardAction
{
    WLMyCardsVController *myCardsController = [[WLMyCardsVController alloc] init];
    [self.navigationController pushViewController:myCardsController animated:YES];
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrProduct.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strProduct = @"productCell";
    WLTelecomProductCell *cell = [tableView dequeueReusableCellWithIdentifier:strProduct];
    if (!cell) {
        cell = [[WLTelecomProductCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strProduct];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    WLTelecomProductModel *telecomProduct = self.arrProduct[indexPath.row];
    [cell.ivHead sd_setImageWithURL:[NSURL URLWithString:telecomProduct.imgPath] placeholderImage:nil];
    cell.labTitle.text = telecomProduct.name;
    cell.labScore.text = [NSString stringWithFormat:@"%@积分",telecomProduct.score];
    if (telecomProduct.enable&&[telecomProduct.score floatValue]<=[self.enableScore floatValue])
    {
        [WLCommonTool addGradientColor:cell.btnExchange fromColor:wlblueColor toColor:wlUIColorRGB(0x2292F5)];
        cell.btnExchange.tag = indexPath.row;
        [cell.btnExchange addTarget:self action:@selector(exchangeScoreAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    else
    {
        NSArray *arrLayers = [NSArray arrayWithArray:cell.btnExchange.layer.sublayers];
        for (CALayer *subLayer in arrLayers) {
            if ([subLayer isKindOfClass:[CAGradientLayer class]])
            {
                [subLayer removeFromSuperlayer];
            }
        }
        [cell.btnExchange setBackgroundColor:wlUIColorRGB(0xE0E0E0)];
        cell.btnExchange.enabled = NO;
    }
    
    return cell;
}

-(void)exchangeScoreAction:(UIButton *)btnExchange
{
    WLTelecomProductModel *product = self.arrProduct[btnExchange.tag];
    WLWkSelf
    NSDictionary *conditions = @{@"score":product.score,@"productId":product.pid,@"rankType":[NSString stringWithFormat:@"%ld",(long)product.rankType]};
    NSDictionary *paramsp = @{@"conditions":conditions};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"product/app/exchange" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        [weakSelf exhangeScoreSuccessWithProduct:product successDict:successDict];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {

    } inView:self.view];
}
- (void)exhangeScoreSuccessWithProduct:(WLTelecomProductModel *)product successDict:(NSDictionary *)successDict {
    CGFloat curScore = self.enableScore.floatValue;
    curScore -= product.score.floatValue;
    self.enableScore = [NSString stringWithFormat:@"%.6f", curScore];
    [self refreshCurrentScore];
    [self showHUDMessage:successDict[@"message"]];
    
}
    
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
